package client

import (
	"errors"
	"fmt"
	"github.com/urfave/cli/v2"
	"io/ioutil"
	"os"
	"sigs.k8s.io/kustomize/kyaml/yaml"
	"strings"
)

func env(ctx *cli.Context) error {
	filename := os.Getenv("GLUE_CONFIG")
	envFile, err := ioutil.ReadFile(filename)
	if err != nil {
		return err
	}

	envMap := make(map[string]string)
	err = yaml.Unmarshal(envFile, &envMap)
	if err != nil {
		return err
	}

	if ctx.NArg() == 0 {
		for k, v := range envMap {
			fmt.Printf("%s=%s\n", k, v)
		}
		return nil
	} else if ctx.Args().Get(0) == "set" {
		keyValue := strings.Split(ctx.Args().Get(1), "=")
		key := keyValue[0]
		value := keyValue[1]
		envMap[key] = value

		newEnvFile, err := yaml.Marshal(envMap)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(filename, newEnvFile, 0666)
		if err != nil {
			return err
		}
	} else {
		return errors.New(fmt.Sprintf("Unexpected instruction %s", ctx.Args().Get(0)))
	}

	return nil
}
